package com.he.DesignPatterns.strategy.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 享元工厂
 * @Author: HCL
 * @Date: 2024/9/3 15:55
 */
public class FlyweightFactory {

    private static final Map<String, Flyweight> flyweightMap = new HashMap<>();

    public static Flyweight getFlyweight(String key) {
        Flyweight flyweight = flyweightMap.get(key);
        if (flyweight == null) {
            switch (key) {
                case "key1":
                    flyweight = new FlyweightA(key);
                    break;
                case "key2":
                    flyweight = new FlyweightB(key);
                    break;
                case "key3":
                    flyweight = new FlyweightC(key);
                    break;
                // 可以添加一个默认分支来处理未知键，例如返回null或抛出异常
                default:
//                    flyweight = null; // 或者抛出一个异常来指示无效的键
//                    break;
                    throw new RuntimeException("创建该对象失败");
            }
            if (flyweight != null) {
                flyweightMap.put(key, flyweight);
            }
        }
            return flyweight;
    }
}
